package oakclub.service;

import oakclub.entity.LocationEntity;
import oakclub.global.Context;
import oakclub.global.Json;
import oakclub.utility.HttpUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class GeoService
{
    private final Logger logger = LoggerFactory.getLogger(GeoService.class);

    private final String URL_GEO_PLUGIN = "http://www.geoplugin.net/json.gp";

    private String getIpAddress()
    {
        return Context.get().getIpAddress();
    }

    public LocationEntity getLocation()
    {
        String ip = this.getIpAddress();
        try
        {
            // send request
            Map<String, Object> params = new HashMap<>();
            params.put("ip", ip);
            String response = HttpUtility.sendGet(this.URL_GEO_PLUGIN, params);

            // check response status
            Map<String, Object> root = Json.getParser().fromJson(response, Map.class);
            int status = ((Double) root.get("geoplugin_status")).intValue();
            if(status != 200)
            {
                throw new Exception(ip + " invalid");
            }

            // parse
            LocationEntity location = new LocationEntity();
            location.setLatitude(Double.valueOf((String) root.get("geoplugin_latitude")));
            location.setLongitude(Double.valueOf((String) root.get("geoplugin_longitude")));
            return location;
        }
        catch(Exception e)
        {
            logger.warn("geo plugin issue", e);
        }

        return null;
    }
}
